package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
/**
 * @description :
 * 自定义订单定时任务调度类
 */
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 订单支付超时处理，通过cron表达式设置定时任务
     */
    //每分钟执行一次该任务
    @Scheduled(cron = "0 */1 * * * ?")
    public void payTask()
    {
        //订单超时业务：
        //1.查询是否有状态为未支付并且创建时间超过15分钟的订单
        //2.如果有，则修改订单状态为取消
        log.info("订单支付超时处理: {}",new Date());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //根据订单的状态和时间查询订单
        List<Orders> ordersList = orderMapper.getByStatusAndCreateTimeBefore(Orders.PENDING_PAYMENT,time);
        //如果存在超时的订单则修改状态
        if(ordersList !=null || ordersList.size()>0)
        {
            ordersList.forEach(order->{
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason(MessageConstant.ORDER_PAY_FAILED);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    /**
     * 订单派送完成处理
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void deliveryTask()
    {
        log.info("订单派送完成处理: {}",new Date());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-1);
        //根据订单的状态和时间查询订单
        List<Orders> ordersList = orderMapper.getByStatusAndCreateTimeBefore(Orders.DELIVERY_IN_PROGRESS,time);
        //如果存在超时的订单则修改状态
        if(ordersList !=null || ordersList.size()>0)
        {
            ordersList.forEach(order-> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
